package com.rdk.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rdk.constant.StrConstant;
import com.rdk.dao.TShareAttachmentMapper;
import com.rdk.dao.TShareMapper;
import com.rdk.dao.TShareMessageMapper;
import com.rdk.dao.TShareUserRelationMapper;
import com.rdk.entity.ShareInteract;
import com.rdk.entity.TShare;
import com.rdk.entity.TShareAttachment;
import com.rdk.entity.TUser;
import com.rdk.service.TShareMessageService;
import com.rdk.service.TShareService;
import com.rdk.service.TShareUserRelationService;
import com.rdk.service.TUserService;
import com.rdk.utils.BusinessException;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.ContentUtil;
import com.rdk.utils.RelativeDateFormat;
import com.rdk.utils.StringUtil;

@Service
public class TShareServiceImpl extends BaseServiceImpl<TShare>  implements TShareService {

	@Autowired
	private TShareMapper mapper;
	
	@Autowired
	private TShareAttachmentMapper shareAttachmentMapper;
	
	@Autowired
	private TShareMessageMapper shareMessageMapper;
	
	@Autowired
	private TShareUserRelationMapper shareUserRelationMapper;
	
	@Autowired
	private TShareMessageService shareMessageService;
	
	@Autowired
	private TUserService userService;
	
	@Autowired
	private TShareUserRelationService shareUserRelationService;
	
    public JSONArray findFeeds(String loginUserId, String timestamp, int offset) {
        // 1、查询是否有某个用户的分享首页缓存，如果有，那么直接从缓存读，否则查询数据库
        // 2、如果有缓存，那么将缓存分享的附件、message信息
        // 3、如果有缓存，操作message表时则需要修改缓存
        // 4、如果用户有缓存，那么他的好友发布分享时则需要更新其缓存
        JSONArray array = new JSONArray();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userId", loginUserId);
        map.put("lastQueryTime", timestamp);
        map.put("offset", offset);
        map.put("rows", StrConstant.PAGE_SIZE);
        List<TShare> shares = mapper.selectFeed(map);
        for (TShare share : shares) {
            share = findShareDetail(share);
            // 消息
            share.setShareInteract(shareMessageService.findShareInteract(loginUserId, share.getShareId()));
            array.add(getShareFeed(share));
        }
        return array;
    }
    
    /**
     * 查询分享详情，不包含评论、回复等
     * 
     * @param share
     * @return
     */
    public TShare findShareDetail(TShare share) {
        if (share != null) {
            // 表情、@的好友
            share.setContent(ContentUtil.parserContent(share.getContent()));
            // 附件
            if ("02".equals(share.getType()) || "03".equals(share.getType())) {// 图片、视频
                List<TShareAttachment> attachments = shareAttachmentMapper.selectByShareId(share.getShareId());
                if (attachments != null && attachments.size() > 0) {
                    if ("03".equals(share.getType())) {// 视频
                        share.setVideo(attachments.get(0).getPath());
                    } else {
                        for (TShareAttachment attachment : attachments) {
                            share.addPic(attachment.getPath());
                        }
                    }
                }
            } else if ("1".equals(share.getType())) {// 转发
            }
        }
        return share;
    }
    
    /**
     * 获取用户分享首页格式的json
     * 
     * @param share
     * @return
     */
    public JSONObject getShareFeed(TShare share) {
        JSONObject json = new JSONObject();
        if (share != null) {
            json.put("id", share.getShareId());
            json.put("original", share.getOriginalShareId());
            json.put("created_at", RelativeDateFormat.format(share.getTime()));
            json.put("text", share.getContent());
            json.put("type", share.getType());
            json.put("scope", share.getScope());
            String address = share.getAddress();
            if (StringUtil.isNotEmpty(address)) {
                json.put("address", address);
            }
            if ("03".equals(share.getType())) {// 视频
                json.put("video", share.getVideo());
            } else if ("02".equals(share.getType())) {// 图片
                json.put("pics", JSONArray.fromObject(share.getPics()));
            } else if ("1".equals(share.getType())) {// 转发
                json.put("retweeted", getShareFeed(findShareById(share.getOriginalShareId())));
            }

            json.put("user", getUserInfo(share));

            ShareInteract interact = share.getShareInteract();
            if (interact != null) {
                json.put("forwarded", interact.isForwarded());
                json.put("commented", interact.isCommented());
                json.put("liked", interact.isLiked());
                json.put("forwards", interact.getForwards());
                json.put("comments", interact.getComments());
                json.put("likes", interact.getLikes());
            }
        } else {
            json.put("id", "-1");
            json.put("created_at", "");
            json.put("text", "该分享已删除！");
            json.put("type", "01");
        }
        return json;
    }
    
    /**
     * 查询分享详情，不包含评论、回复等
     * 
     * @param shareId
     * @return
     */
    public TShare findShareById(String shareId) {
        return findShareDetail(mapper.selectByPrimaryKey(shareId));
    }
	
    
    /**
     * 查询单个分享，评论分组显示
     * 
     * @param shareId
     * @param loginUserId
     * @return
     */
    public JSONObject findFeed(String shareId, String loginUserId) throws BusinessException {
        TShare share = findShareById(shareId);
        if (share == null) {
            throw new BusinessException("该分享已删除！");
        }
        // 消息
        share.setShareInteract(shareMessageService.findShareInteract(loginUserId, share.getShareId()));

        JSONObject json = getShareFeed(share);
        JSONArray comments = json.getJSONArray("comments");
        shareMessageService.commentGroup(comments);

        return json;
    }
    
    /**
     * 查询用户的分享
     * 
     * @param userId
     * @param loginUserId
     * @param timestamp
     * @param offset
     * @return
     */
    public JSONArray findUserShare(String userId, String loginUserId, String timestamp, int offset) {
        JSONArray array = new JSONArray();
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("userId", userId);
        map.put("lastQueryTime", timestamp);
        map.put("offset", offset);
        map.put("rows", StrConstant.PAGE_SIZE);
        List<TShare> shares = mapper.selectFeedByUser(map);
        for (TShare share : shares) {
            share = findShareDetail(share);
            // 消息
            share.setShareInteract(shareMessageService.findShareInteract(loginUserId, share.getShareId()));
            array.add(getShareFeed(share));
        }
        return array;
    }
    
    /**
     * 查询用户的分享
     * 
     * @param name
     * @param loginUserId
     * @param timestamp
     * @param offset
     * @return
     */
    public JSONArray findUserShareByName(String name, String loginUserId, String timestamp, int offset)
            throws BusinessException {
        TUser user = userService.findUserByName(name);
        if (user == null) {
            throw new BusinessException("用户不存在！");
        }
        return this.findUserShare(user.getUserId(), loginUserId, timestamp, offset);
    }
    
    /**
     * 新增
     * 
     * @param reqBean
     */
    public void addShare(HttpServletRequest request,String userId) throws BusinessException {
        TShare share = new TShare();
        share.setShareId(getIntId());
        share.setUserId(userId);
        share.setContent(CommonUtil.getRequest(request, "content"));
        share.setType(CommonUtil.getRequest(request, "type"));
        share.setTime(new Date());
        share.setLatitude(Double.valueOf(CommonUtil.getRequest(request, "latitude")));
        share.setLongitude(Double.valueOf(CommonUtil.getRequest(request, "longitude")));
        share.setAddress(CommonUtil.getRequest(request, "address"));

        // 附件
        if (Integer.valueOf(CommonUtil.getRequest(request, "fileCount")) > 0) {
            String[] files = CommonUtil.getRequest(request, "files").split(",");
            List<TShareAttachment> list = new ArrayList<TShareAttachment>();
            for (int i = 0; i < files.length; i++) {
                TShareAttachment attachment = new TShareAttachment();
                attachment.setAttachmentId(getIntId());
                attachment.setShareId(share.getShareId());
                attachment.setUserId(share.getUserId());
                attachment.setType(CommonUtil.getRequest(request, "atype"));
                attachment.setPath(files[i]);
                attachment.setOrderNum(i + 1);
                attachment.setTime(share.getTime());
                list.add(attachment);
            }
            shareAttachmentMapper.insertBatch(list);
        }
        // 分组
        String scope = CommonUtil.getRequest(request, "scope");// 1、可见 2、不可见
        share.setScope(scope);
        shareUserRelationService.saveShareScope(share.getShareId(), share.getUserId(), scope,
        		CommonUtil.getRequest(request, "groupId"));
        mapper.insertSelective(share);

        // @好友
        List<String> atUsers = ContentUtil.getAtUsers(share.getContent());
        shareMessageService.at(share.getShareId(), userId, atUsers);
    }
    
    /**
     * 删除自己的分享
     * 
     * @param shareId
     * @param loginUserId
     */
    @Transactional
    public void deleteShare(String shareId, String loginUserId) throws BusinessException {
        TShare share = mapper.selectByPrimaryKey(shareId);
        if (share == null) {
            throw new BusinessException("获取分享失败");
        }
        if (share.getUserId().equals(loginUserId)) {
            mapper.deleteByPrimaryKey(shareId);
            shareAttachmentMapper.deleteByShareId(shareId);
            shareMessageMapper.deleteByShareId(shareId);
            shareUserRelationMapper.deleteByShareId(shareId);
        }
    }
    
    /**
     * 转发
     * 
     * @param refer
     * @param reqBean
     */
    public void forward(String refer, HttpServletRequest request,String userId) throws BusinessException {
        String commentTo = CommonUtil.getRequest(request, "commentTo");
        if (StringUtil.isEmpty(refer) || StringUtil.isEmpty(commentTo)) {
            throw new BusinessException("获取分享失败");
        }
        TShare share = new TShare();
        share.setShareId(getIntId());
        share.setUserId(userId);
        share.setContent(CommonUtil.getRequest(request, "content"));
        share.setType("1");// 转发
        share.setTime(new Date());
        share.setLatitude(Double.valueOf(CommonUtil.getRequest(request, "latitude")));
        share.setLongitude(Double.valueOf(CommonUtil.getRequest(request, "longitude")));
        share.setAddress(CommonUtil.getRequest(request, "address"));
        share.setReferencedShareId(refer);
        String original = CommonUtil.getRequest(request, "original");
        if (StringUtils.equals(original, "0")) {
            original = refer;// 第一次转发
        }
        share.setOriginalShareId(original);
        // 分组
        String scope = CommonUtil.getRequest(request, "scope");// 1、可见 2、不可见
        share.setScope(scope);
        shareUserRelationService.saveShareScope(share.getShareId(), share.getUserId(), scope,
        		CommonUtil.getRequest(request, "groupId"));
        mapper.insertSelective(share);

        // 转发消息
        shareMessageService.forward(refer, commentTo, userId);

        // 同时评论
        if ("1".equals(CommonUtil.getRequest(request, "isComment"))) {
            shareMessageService.comment(refer, request,userId);
        } else {
            // @好友
            List<String> atUsers = ContentUtil.getAtUsers(share.getContent());
            shareMessageService.at(share.getShareId(), userId, atUsers);
        }
    }
    
    public JSONObject getUserInfo(TShare share) {
        JSONObject json = new JSONObject();
        json.put("id", share.getUserId());
        json.put("name", share.getUserName());
        json.put("avatar", share.getUserAvatar());
        return json;
    }
}